﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using LocalService = Sunboxsoft.ASMS.Client.Domain.LocalService;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Create
{
    /// <summary>
    /// 创建资金入账单
    /// </summary>
    public partial class CreateCapitalIncreaseView : UserControl, IView
    {
        #region fields
        Promise _promise = new Promise();
        /// <summary>
        /// 支付渠道
        /// </summary>
        List<WebRef.EPayRecord> _listPayRecord = new List<WebRef.EPayRecord>();
        /// <summary>
        /// 相关单号获取
        /// </summary>
        WebRef.EBillHeader _billHeader = null;
        WebRef.VCustomer _customer = null;
        #endregion

        public CreateCapitalIncreaseView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(this.ctlSearchLookUpEditBillType, "单据类型"));
            ValidationManager.Register(this, new Common.Validations.LookUpEditValidation(this.ctlLookUpPayMan, "付款方"));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.txtOther, "付款人", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.txtAboutNum, "相关单号", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.txtRemark, "入账备注", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.txtTicketNumber, "票据号码", true));
        }

        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("save", Resources.isOK, "保存", OnActionSaveClick))
               .AddAction(new ActionNode("cancel", Resources.isBack, "取消", OnActionCancelClick));
        }
        public void Active(ViewActiveArgs args)
        {
            _promise.Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    ctlSearchLookUpEditBillType.BindIntCodeTextItem(Domain.Constant.CapitalChangedType.EnumerateIncrease(), null, false);
                    _promise.Resolve();
                }));
            })
            .Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    this.ctlLookUpPayMan.BindIntCodeTextItem(Domain.Constant.CapitalRoleTypes.EnumerateIncrease(),
                        Domain.Constant.CapitalRoleTypes.CustomerItem, false);
                    _promise.Resolve();
                }));
            })
            .Then(() =>
            {
                ctlSearchLookIpEditPayChanel.BindEMasterDataItem(_promise,
                    Domain.Constant.MasterDataCodes.PayChannel, null, null, false, true);
            }).Then(() =>
            {
                ctlSearchLookUpEditInvoiceType.BindEMasterDataItem(_promise,
                    Domain.Constant.MasterDataCodes.InvoiceTypes, null, null, false, true);
            })
            .Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    InitInfo();
                    _promise.Resolve();
                }));
            })
            .Run();
        }
        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs != null && args.ClosedArgs.Result)
            {
                if (args.ClosedArgs.View is Pickers.VCustomerAccuratelyPicker)
                {
                    _customer = args.ClosedArgs.Data as WebRef.VCustomer;
                    ctlEditCustomer.Text = _customer.Name;
                }
            }
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("新建资金入账单");
        }
        #endregion

        #region Method
        /// <summary>
        /// 数据加载
        /// </summary>
        private void InitInfo()
        {
            this.lblCustomer.Visible = true;
            this.ctlEditCustomer.Visible = true;
            this.lblSupplyer.Visible = false;
            this.selectLupSupplyer.Visible = false;
            this.lblStaff.Visible = false;
            this.selectLupStaff.Visible = false;
            this.lblOther.Visible = false;
            this.txtOther.Visible = false;
        }
        /// <summary>
        /// 获取选择的供应商
        /// </summary>
        /// <returns></returns>
        private WebRef.VSupplier GetSelectSupplier()
        {
            return this.selectLupSupplyer.EditValue as WebRef.VSupplier;
        }
        /// <summary>
        /// 获取选择的员工
        /// </summary>
        /// <returns></returns>
        private WebRef.EStaff GetSelectStaff()
        {
            return this.selectLupStaff.EditValue as WebRef.EStaff;
        }
        /// <summary>
        /// 数据检查
        /// </summary>
        /// <returns></returns>
        private bool ValidateData()
        {
            string strMess = "";
            if (!ValidationManager.Validate(this, out strMess))
            {
                UIContext.Current.ViewManager.ShowInfo(strMess);
                return false;
            }
            else
            {
                switch (this.ctlLookUpPayMan.GetSelectedValue<Domain.IntCodeTextItem>().GetCode())
                {
                    case Domain.Constant.CapitalRoleTypes.Customer:
                        if (_customer == null)
                        {
                            UIContext.Current.ViewManager.ShowWarning("请选择客户！");
                            return false;
                        }
                        break;
                    case Domain.Constant.CapitalRoleTypes.Supplier:
                        if (GetSelectSupplier() == null)
                        {
                            UIContext.Current.ViewManager.ShowWarning("请选择供应商！");
                            return false;
                        }
                        break;
                    case Domain.Constant.CapitalRoleTypes.Staff:
                        if (GetSelectStaff() == null)
                        {
                            UIContext.Current.ViewManager.ShowWarning("请选择员工！");
                            return false;
                        }
                        break;
                    case Domain.Constant.CapitalRoleTypes.Other:
                        if (string.IsNullOrEmpty(this.txtOther.Text.Trim()))
                        {
                            UIContext.Current.ViewManager.ShowWarning("请输入付款人！");
                            return false;
                        }
                        break;
                }
            }
            if (this._listPayRecord.Count == 0)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择收款渠道！");
                return false;
            }
            if (GetListPayRecord() == null)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取已添加的所有的支付方式
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EPayRecord> GetListPayRecord()
        {
            List<WebRef.EPayRecord> list = this.GVData.DataSource as List<WebRef.EPayRecord>;
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].PayAmount <= 0)
                {
                    UIContext.Current.ViewManager.ShowWarning("支付金额应大于0！");
                    return null;
                }
            }
            return list;
        }
        /// <summary>
        /// 创建资金入账单
        /// </summary>
        private void CreateCapticalIncreaseBill()
        {
            int payMentRoleType = this.ctlLookUpPayMan.GetSelectedValue<Domain.IntCodeTextItem>().GetCode();

            WebRef.ECapitalIncreaseBill bill = new WebRef.ECapitalIncreaseBill();
            bill.BusinessId = ModuleContext.Current.BusinessId.Value;
            bill.StationId = ModuleContext.Current.StationId.Value;
            bill.ChangedType = this.ctlSearchLookUpEditBillType.GetSelectedValue<Domain.IntCodeTextItem>().GetCode();
            bill.Amount = Convert.ToDecimal(this.txtAmount.Text.Trim());
            bill.PayerRoleType = payMentRoleType;
            switch (payMentRoleType)
            {
                case Domain.Constant.CapitalRoleTypes.Customer:
                    bill.PayerRole = _customer.Id.ToString();
                    break;
                case Domain.Constant.CapitalRoleTypes.Supplier:
                    bill.PayerRole = GetSelectSupplier().Id.ToString();
                    break;
                case Domain.Constant.CapitalRoleTypes.Staff:
                    bill.PayerRole = GetSelectStaff().Id.ToString();
                    break;
                case Domain.Constant.CapitalRoleTypes.Other:
                    bill.PayerRole = this.txtOther.Text.Trim();
                    break;
            }
            if (_billHeader != null)
            {
                bill.BillNumber = this.txtAboutNum.Text.Trim();
                bill.BillId = _billHeader.BillId;
                bill.BillType = _billHeader.BillType;
            }
            else
            {
                bill.BillNumber = this.txtAboutNum.Text.Trim();
                bill.BillType = Domain.Constant.BillTypes.Other;
            }
            bill.InvoiceType = ctlSearchLookUpEditInvoiceType.GetSelectedValue<WebRef.EMasterDataItem>().GetCode();
            bill.InvoiceNumber = this.txtTicketNumber.Text.Trim();
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.CreateService().CreateCapticalIncreaseBill(bill, GetListPayRecord().ToArray());
                this.BeginInvoke(new Action<ServiceResult>((p) =>
                {
                    if (p.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, null);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                        _promise.Reject();
                    }
                }), result);
            });
        }
        /// <summary>
        /// 根据相关单号获取相关信息
        /// </summary>
        private void GetBillHeader()
        {
            UIContext.Current.InvokeAsync(() =>
            {
                ListResult<WebRef.EBillHeader> result = new Service.QueryService().QueryBillHeaderList(this.txtAboutNum.Text.Trim());
                this.BeginInvoke(new Action<ListResult<WebRef.EBillHeader>>((p) =>
                {
                    if (p.IsSuccess)
                    {
                        if (p.Data.Items.Count > 0)
                        {
                            _billHeader = p.Data.Items[0];
                            this.picture.Visible = true;
                            this.picture.Image = Resources.isOK;
                            this.picture.ToolTip = "已找到该单号！";
                        }
                        else
                        {
                            this.picture.Visible = true;
                            this.picture.Image = Resources.isDelete;
                            this.picture.ToolTip = "未找到该单号！";
                        }
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                        _promise.Reject();
                    }
                }), result);
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnActionSaveClick(object sender, object e)
        {
            if (ValidateData())
            {
                CreateCapticalIncreaseBill();
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnActionCancelClick(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(true, null);
        }
        /// <summary>
        /// 根据可输入的相关单号显示图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtAboutNum_EditValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtAboutNum.Text.Trim()))
            {
                GetBillHeader();
            }
        }
        /// <summary>
        /// 添加收银方式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddPayWay_Click(object sender, EventArgs e)
        {
            WebRef.EMasterDataItem emdItem = this.ctlSearchLookIpEditPayChanel.EditValue as WebRef.EMasterDataItem;
            if (emdItem != null)
            {
                WebRef.EPayRecord item = new WebRef.EPayRecord(emdItem.Code, emdItem.Name, 0, "");
                _listPayRecord.Add(item);
                this.GCCashInfo.DataSource = null;
                this.GCCashInfo.DataSource = _listPayRecord;
            }
        }
        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RIButtonRemove_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Caption == "移除")
            {
                WebRef.EPayRecord item = this.GVData.GetRow(GVData.FocusedRowHandle) as WebRef.EPayRecord;
                _listPayRecord.Remove(item);
                if (_listPayRecord.Count == 0)
                {
                    this.GCCashInfo.DataSource = null;
                }
                else
                {
                    this.GCCashInfo.DataSource = null;
                    this.GCCashInfo.DataSource = _listPayRecord;
                }
            }
        }
        /// <summary>
        /// 根据对应的付款方显示对应的数据源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlLookUpPayMan_EditValueChanged(object sender, EventArgs e)
        {
            int selectedItemCode = this.ctlLookUpPayMan.GetSelectedValue<Domain.IntCodeTextItem>().GetCode();

            if (selectedItemCode == Domain.Constant.CapitalRoleTypes.Customer)
            {
                this.lblCustomer.Visible = true;
                this.ctlEditCustomer.Visible = true;
                this.lblSupplyer.Visible = false;
                this.selectLupSupplyer.Visible = false;
                this.lblStaff.Visible = false;
                this.selectLupStaff.Visible = false;
                this.lblOther.Visible = false;
                this.txtOther.Visible = false;
            }
            else if (selectedItemCode == Domain.Constant.CapitalRoleTypes.Supplier)
            {
                this.lblCustomer.Visible = false;
                this.ctlEditCustomer.Visible = false;
                this.lblSupplyer.Visible = true;
                this.selectLupSupplyer.Visible = true;
                this.lblStaff.Visible = false;
                this.selectLupStaff.Visible = false;
                this.lblOther.Visible = false;
                this.txtOther.Visible = false;
                if (this.selectLupSupplyer.Properties.DataSource == null)
                {
                    this._promise.Then(() =>
                    {
                        this.ShowMask();
                        _promise.Resolve();
                    }).Then(() =>
                    {
                        this.selectLupSupplyer.BindVSupplier(_promise, false, true);
                    }).Then(() =>
                    {
                        this.HideMask();
                        _promise.Resolve();
                    }).Run();
                }
            }
            else if (selectedItemCode == Domain.Constant.CapitalRoleTypes.Staff)
            {
                this.lblCustomer.Visible = false;
                this.ctlEditCustomer.Visible = false;
                this.lblSupplyer.Visible = false;
                this.selectLupSupplyer.Visible = false;
                this.lblStaff.Visible = true;
                this.selectLupStaff.Visible = true;
                this.lblOther.Visible = false;
                this.txtOther.Visible = false;
                if (this.selectLupStaff.Properties.DataSource == null)
                {
                    this._promise.Then(() =>
                    {
                        this.ShowMask();
                        _promise.Resolve();
                    }).Then(() =>
                    {
                        this.selectLupStaff.BindEStaff(_promise, false, true);
                    }).Then(() =>
                    {
                        this.HideMask();
                        _promise.Resolve();
                    }).Run();
                }
            }
            else
            {
                this.lblCustomer.Visible = false;
                this.ctlEditCustomer.Visible = false;
                this.lblSupplyer.Visible = false;
                this.selectLupSupplyer.Visible = false;
                this.lblStaff.Visible = false;
                this.selectLupStaff.Visible = false;
                this.lblOther.Visible = true;
                this.txtOther.Visible = true;
            }
        }
        /// <summary>
        /// 选择客户&清除客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlEditCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.Equals("clear"))
            {
                this.ctlEditCustomer.Text = "";
                _customer = null;
            }
            else
            {
                UIContext.Current.ViewManager.PopupView(new Pickers.VCustomerAccuratelyPicker(), new PopupViewArgs(null));
            }
        }
        #endregion
    }
}
